﻿using Microsoft.SqlServer.Server;
//------------------------------------------------------------------------------
// <copyright file="CSSqlFunction.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace Inovout.Cloud.Search.Sqlserver
{
    public class SearchFunction
    {
        [SqlFunction(TableDefinition = "id nvarchar(200)", FillRowMethodName = "FillRow")]
        public static IEnumerable Cloud_Contains(string key, string keyword, string indexNames, string typeNames, string fieldNames, int pageIndex, int pageSize)
        {
            if (String.IsNullOrEmpty(keyword))
            {
                return null;
            }
            string requestUrl = "http://172.10.2.190:8081/search/fs";
            if (!String.IsNullOrEmpty(indexNames))
            {
                requestUrl = requestUrl + "/" + indexNames;
            }
            if (!String.IsNullOrEmpty(typeNames))
            {
                requestUrl = requestUrl + "/" + typeNames;
            }
            if (!String.IsNullOrEmpty(fieldNames))
            {
                requestUrl = requestUrl + "/" + fieldNames;
            }

            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }

            if (pageSize <= 0)
            {
                pageSize = 10;
            }

            requestUrl = requestUrl + "?" + "pageSize=" + pageSize + "&pageIndex=" + pageIndex + "&isGetIds=true&q=" + keyword + "&key=" + key;
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
                if (!string.IsNullOrEmpty(result))
                {
                    List<string> list = new List<string>();
                    string[] ids = result.Replace("\"", "").Split(',');
                    foreach (string str in ids)
                    {
                        list.Add(str);
                    }
                    return list;
                }
            }
            return null;
        }

        public static void FillRow(object row, out string id)
        {
            id = (String)row;
        }
    }
}
